class Solution
{
public:
    string smallestSubsequence(string s)
    {
        unordered_map<char, int> finalOccur;
        int n = s.size();
        for (int i = 0; i < n; ++i)
        {
            finalOccur[s[i]] = i;
        }
        string result;
        int existChar = 0;
        for (int i = 0; i < n; ++i)
        {
            while (!result.empty())
            {
                if (!(existChar & (1 << (s[i] - 'a'))) && result.back() > s[i] && finalOccur[result.back()] > i)
                {
                    existChar &= ~(1 << (result.back() - 'a'));
                    result.pop_back();
                }
                else
                {
                    break;
                }
            }
            if (!(existChar & (1 << (s[i] - 'a'))))
            {
                result.push_back(s[i]);
                existChar |= 1 << (s[i] - 'a');
            }
        }
        return result;
    }
};